package com.caowei.weicimpress.weicimpress;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.caowei.weicimpress.weicimpress.widget.DeflateGridView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.OnFocusChange;
import butterknife.OnItemClick;

/**
 * Created by caoweiPc on 2014/7/25.
 */
public  class OperationCompressActivity extends InputBaseActivity implements AdapterView.OnItemClickListener ,
EditText.OnFocusChangeListener,View.OnClickListener{
    @InjectView(R.id.list)
    ListView list_handers;
    @InjectView(R.id.list_arithmetic)
    DeflateGridView gridview_arithmetic;
    @InjectView(R.id.compressmethod)
    LinearLayout compressmethod;
    @InjectView(R.id.encrypt)
    LinearLayout encrypt;
    @InjectView(R.id.passwd)
    EditText passwd;
    @InjectView(R.id.subsize)
    EditText subsize;
    @InjectView(R.id.passwd_close)
    ImageView passwd_close;
    @InjectView(R.id.subsize_close)
    ImageView subsize_close;
    TextView selectedUnit;
    @InjectView(R.id.unit1)
    TextView unit1;
    @InjectView(R.id.unit2)
    TextView unit2;
    @InjectView(R.id.unit3)
    TextView unit3;
    @InjectView(R.id.unit4)
    TextView unit4;
    @InjectView(R.id.saveNameLayout)
    LinearLayout saveNameLayout;
    @InjectView(R.id.saveName)
    EditText saveName;
    @InjectView(R.id.saveName_close)
    ImageView saveName_close;
    private FileInfoBean bean;
    private ArrayList<FileInfoBean> beans;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.operationactivity_layout);
        ButterKnife.inject(this);

        Intent intent=this.getIntent();
        bean=this.getIntent().getParcelableExtra("bean");
        beans=this.getIntent().getParcelableArrayListExtra("beans");
        if(bean==null){
            bean=beans.get(0);
        }
        actiobarPath.setText(Utils.normalizePath(bean.getParentPath()+ File.separator+
        bean.getFileName()));

        //todo 以后做吧============================恢复原状的参数==========================
        FileInfoBean compressedFileBean=intent.getParcelableExtra("bean");
        String fileHandlerClsName=intent.getStringExtra("handler");
        FileHandler fileHandler=null;
        if(!TextUtils.isEmpty(fileHandlerClsName)){
            fileHandler=ExecuteFileHandler.getInstance().
                    getHandlerByClsName(fileHandlerClsName);
        }
        String passwd=intent.getStringExtra("passwd");
        int compressmethod_key=intent.getIntExtra("compressmethod_key",-1);
        int subsize=intent.getIntExtra("subsize",-1);
        String unit=intent.getStringExtra("selectedUnit");
        String saveName=intent.getStringExtra("saveName");
      //======================================================

        final List<FileHandler> supportCompressHandlers= ExecuteFileHandler.getInstance().getSupportCompressHandlers();
        //todo
        BaseAdapter adapter1=new BaseAdapter() {
            @Override
            public int getCount() {
                return supportCompressHandlers.size();
            }

            @Override
            public String getItem(int position) {
                return supportCompressHandlers.get(position).getNameOfFormat();
            }

            @Override
            public long getItemId(int position) {
                return supportCompressHandlers.get(position).getNameOfFormat().hashCode();
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder viewHolder=null;
                if(convertView==null){
                    View v=LayoutInflater.from(OperationCompressActivity.this).
                            inflate(R.layout.formater_item,parent,false);
                    viewHolder=new ViewHolder(v);
                    convertView=v;
                    convertView.setTag(viewHolder);
                }else{
                    viewHolder= (ViewHolder) convertView.getTag();
                }
                String formateName=getResources().getString(R.string.formater_name,getItem(position));
                viewHolder.textView.setText(formateName);
                viewHolder.setFileHandler(supportCompressHandlers.get(position));
                return convertView;
            }
        };

        list_handers.setAdapter(adapter1);
        //todo ======================================

        CompressMethodAdapter adapter2=new CompressMethodAdapter();
        adapter2.setmData(new ArrayList<Map.Entry<Integer,String>>());
        gridview_arithmetic.setAdapter(adapter2);

        //todo ======================================
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if(hasFocus){
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    list_handers.performItemClick(
                            list_handers.getChildAt(0),
                            0,
                            list_handers.getAdapter().getItemId(0)
                    );

                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            gridview_arithmetic.performItemClick(
                                    gridview_arithmetic.getChildAt(0),
                                    0,
                                    gridview_arithmetic.getAdapter().getItemId(0)
                            );
                        }
                    });

                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            unit3.performClick();
                        }
                    });
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

  /*  @Override
    protected void initactioBar() {
        ActionBar actionBar=getSupportActionBar();
        bar=actionBar;
        actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE|ActionBar.DISPLAY_USE_LOGO);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        View v= LayoutInflater.from(this).inflate(R.layout.actionbar_custom1,null,false);
        actionBar.setCustomView(v);
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME
                |ActionBar.DISPLAY_SHOW_CUSTOM|ActionBar.DISPLAY_HOME_AS_UP);
    }
*/
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @OnItemClick({R.id.list,R.id.list_arithmetic})
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        int parentId=parent.getId();
        switch (parentId){
            case R.id.list:
                ViewHolder preViewHolder= (ViewHolder) parent.getTag();
                if(preViewHolder!=null&&preViewHolder.equals(view.getTag())){
                    return;
                }
                if(preViewHolder!=null){
                    TextView preTextView= preViewHolder.textView;
                    Drawable drawableleft2=this.getResources().getDrawable(R.drawable.selected_2);
                    Rect rect=new Rect(0,0,drawableleft2.getIntrinsicWidth(),
                            drawableleft2.getIntrinsicHeight());
                    drawableleft2.setBounds(rect);
                    preTextView.setCompoundDrawables(drawableleft2,null,null,null);
                    preTextView.setTextColor(getResources().getColor(R.color.gray_deep));
                }
                ViewHolder viewHolder= (ViewHolder) view.getTag();

                TextView textView= viewHolder.textView;
                Drawable drawableleft=this.getResources().getDrawable(R.drawable.selected_1);
                Rect rect=new Rect(0,0,drawableleft.getIntrinsicWidth(),
                        drawableleft.getIntrinsicHeight());
                drawableleft.setBounds(rect);
                textView.setCompoundDrawables(drawableleft, null, null, null);
                textView.setTextColor(this.getResources().getColor(R.color.green_deep));
                parent.setTag(viewHolder);
                FileHandler fileHandler=viewHolder.fileHandler;
                Map<Integer,String> deflateMethod= fileHandler.getDeflate_method();
                if(deflateMethod.size()>0){
                    if(compressmethod.getVisibility()!=View.VISIBLE){
                        compressmethod.setVisibility(View.VISIBLE);
                    }
                    CompressMethodAdapter adapter= (CompressMethodAdapter) gridview_arithmetic.getAdapter();
                    Set<Map.Entry<Integer,String>> set= deflateMethod.entrySet();
                    List<Map.Entry<Integer,String>> list=new ArrayList<Map.Entry<Integer, String>>(set);
                    adapter.setmData(list);
                    adapter.notifyDataSetChanged();
                }
                if(fileHandler.isSurpportCryptogram()){
                    if(encrypt.getVisibility()!=View.VISIBLE){
                        encrypt.setVisibility(View.VISIBLE);
                    }
                }
                //todo
                break;
            case R.id.list_arithmetic:
                ViewHolder  selectHolder= (ViewHolder) parent.getTag();
                ViewHolder currentHolder= (ViewHolder) view.getTag();
                if(selectHolder!=null){
                   Drawable drawable=getResources().getDrawable(R.drawable.selected_2);
                   Rect rect1=new Rect(0,0,drawable.getIntrinsicWidth(),
                           drawable.getIntrinsicHeight());
                   drawable.setBounds(rect1);
                    selectHolder.textView.setCompoundDrawables(null, drawable, null, null);
                    selectHolder.textView.setTextColor(getResources().getColor(R.color.gray_deep));
                }
                Drawable drawable2=getResources().getDrawable(R.drawable.selected_1);
                Rect rect2=new Rect(0,0,drawable2.getIntrinsicWidth(),
                        drawable2.getIntrinsicHeight());
                drawable2.setBounds(rect2);
                currentHolder.textView.setCompoundDrawables(null, drawable2, null, null);
                currentHolder.textView.setTextColor(getResources().getColor(R.color.green_deep));
                parent.setTag(currentHolder);
                break;
        }
    }

    @OnFocusChange({R.id.passwd,R.id.subsize})
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        InputMethodManager inmm= (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if(hasFocus){
            inmm.showSoftInput(v,InputMethodManager.SHOW_IMPLICIT);
        }else{
            inmm.hideSoftInputFromWindow(v.getWindowToken(),InputMethodManager.HIDE_IMPLICIT_ONLY);
        }
    }

    @OnClick({R.id.subsize_close,R.id.passwd_close,
    R.id.unit1,R.id.unit2,R.id.unit3,R.id.unit4,R.id.ok,R.id.saveName_close})
    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id){
            case R.id.subsize_close:
                subsize.setText("");
                break;
            case R.id.passwd_close:
                passwd.setText("");
                break;
            case R.id.unit1:
                selectUnit(unit1);
                break;
            case R.id.unit2:
                selectUnit(unit2);
                break;
            case R.id.unit3:
                selectUnit(unit3);
                break;
            case R.id.unit4:
                selectUnit(unit4);
                break;
            case R.id.saveName_close:
                saveName.setText("");
                break;
            case R.id.ok:
                Intent i=new Intent();
                ViewHolder hander_ViewHandler= (ViewHolder) list_handers.getTag();
                if(hander_ViewHandler!=null){
                    i.putExtra("handler",hander_ViewHandler.fileHandler.getClass().getName());
                }
                i.putExtra("passwd", passwd.getText().toString());
                ViewHolder compressMethodHolder= (ViewHolder) gridview_arithmetic.getTag();
                if(compressMethodHolder!=null){
                    i.putExtra("compressmethod_key", (Integer) compressMethodHolder.textView.getTag());
                }
                String subsizeV= subsize.getText().toString();
                if(!TextUtils.isEmpty(subsizeV)){
                    i.putExtra("subsize",Integer.parseInt(subsizeV));
                }
                if(selectedUnit!=null){
                    i.putExtra("selectedUnit",selectedUnit.getText());
                }else{
                    i.putExtra("selectedUnit",Utils.UNITS[2]);
                }
                String saveNameStr=Utils.dropDotSuffix(bean.getFileName());
                if(!TextUtils.isEmpty(saveName.getText().toString())){
                    saveNameStr=saveName.getText().toString();
                }

                String nameOfFormat=hander_ViewHandler.getFileHandler().getNameOfFormat();
                i.putExtra("saveName",saveNameStr);
                i.putExtra("nameOfFormat",nameOfFormat);
                i.putExtra("bean",bean);
                i.putParcelableArrayListExtra("beans",beans);
                setResult(Activity.RESULT_OK,i);
                finish();
                break;
        }
    }

    private void selectUnit(TextView unit){
        if(selectedUnit!=null){
            selectedUnit.setTextColor(getResources().getColor(R.color.gray_deep));
            Drawable drawable=getResources().getDrawable(R.drawable.selected_2);
            Rect rect=new Rect(0,0,drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
            drawable.setBounds(rect);
            selectedUnit.setCompoundDrawables(null,drawable,null,null);
        }
        unit.setTextColor(getResources().getColor(R.color.green_deep));
        Drawable drawable=getResources().getDrawable(R.drawable.selected_1);
        Rect rect=new Rect(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
        drawable.setBounds(rect);
        unit.setCompoundDrawables(null,drawable,null,null);
        selectedUnit=unit;
    }

    private   class CompressMethodAdapter extends BaseAdapter{
        private List<Map.Entry<Integer,String>> mData;
        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Map.Entry<Integer,String> getItem(int position) {
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return getItem(position).hashCode();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder=null;
            if(convertView==null){
                View v=  LayoutInflater.from(OperationCompressActivity.this).inflate(R.layout.arithmetic_item,parent,false);
                convertView=v;
                viewHolder=new ViewHolder(v);
                v.setTag(viewHolder);
            }else{
                viewHolder= (ViewHolder) convertView.getTag();
            }
            viewHolder.textView.setText(getItem(position).getValue());
            viewHolder.textView.setTag(getItem(position).getKey());
            return convertView;
        }

        public List<Map.Entry<Integer,String>> getmData() {
            return mData;
        }

        public void setmData(List<Map.Entry<Integer,String>> mData) {
            this.mData = mData;
        }
    };

    static class ViewHolder{
        @InjectView(R.id.text)
        TextView textView;
        private FileHandler fileHandler;
        public ViewHolder(View v){
//            textView= (TextView) v.findViewById(R.id.text);
            ButterKnife.inject(this,v);
        }

        public FileHandler getFileHandler() {
            return fileHandler;
        }

        public void setFileHandler(FileHandler fileHandler) {
            this.fileHandler = fileHandler;
        }
    }
}
